package com.wmh.baseservice.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.wmh.baseservice.admin.cache.permission.AdRoleRepository;
import com.wmh.baseservice.admin.entity.AdUserRole;
import com.wmh.baseservice.admin.mapper.AdUserRoleMapper;
import com.wmh.baseservice.admin.service.AdUserRoleService;
import com.wmh.baseservice.common.mybatisplus.methods.CommonServiceImpl;
import com.wmh.baseservice.common.mybatisplus.structure.LambdaQueryWrapperX;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wmh generator
 * @since 2023-02-17
 */
@Service
public class AdUserRoleServiceImpl extends CommonServiceImpl<AdUserRoleMapper, AdUserRole> implements AdUserRoleService {

    @Resource
    private AdRoleRepository adRoleRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setRoleIds(Long adId, List<Long> roleIds) {
        delete(adId);
        List<AdUserRole> entityList = CollUtil
                .map(roleIds, i -> new AdUserRole().setAdId(adId).setRoleId(i), true);
        saveBatch(entityList);
        adRoleRepository.setRoleIds(adId,roleIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long adId) {
        baseMapper.delete(new LambdaQueryWrapperX<AdUserRole>()
                .eq(AdUserRole::getAdId,adId));
        adRoleRepository.del(adId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(Long... roleIds) {
        baseMapper.delete(new LambdaQueryWrapperX<AdUserRole>()
                .in(AdUserRole::getRoleId, Arrays.stream(roleIds).toArray()));
        adRoleRepository.delRoleIds(Arrays.stream(roleIds).collect(Collectors.toList()));
    }

    @Override
    public List<Long> getRoleIdsByCache(Long adId) {
        List<Long> roleIds = adRoleRepository.getRoleIds(adId);
        if (CollUtil.isEmpty(roleIds)) {
            roleIds = baseMapper.getRoleIds(adId);
            adRoleRepository.setRoleIds(adId, roleIds);
        }
        return roleIds;
    }
}
